/**
 * @(#)DOrder
 * 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究
 *
 *<br> Copyright:  Copyright (c) 2014
 *<br> Company:厦门畅享信息技术有限公司
 *<br> @author ulyn
 *<br> 14-8-16 下午1:20
 *<br> @version 1.0
 *————————————————————————————————
 *修改记录
 *    修改者：
 *    修改时间：
 *    修改原因：
 *————————————————————————————————
 */
package cn.ulyn.seckill.mockclient;

import cn.ulyn.seckill.servlet.MockHttpServletRequest;
import cn.ulyn.seckill.util.DESede;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.TreeMap;

/**
 * <pre></pre>
 * <br>----------------------------------------------------------------------
 * <br> <b>功能描述:</b>
 * <br>
 * <br> 注意事项:
 * <br>
 * <br>
 * <br>----------------------------------------------------------------------
 * <br>
 */
public class SeckillOrderCreator {

    HttpServletRequest request;
    JSONObject seckillQstBean;
    JSONObject stockBean;
    String answer;

    protected TreeMap<String, String> params = new TreeMap();

    public SeckillOrderCreator(JSONObject seckillQstBean, JSONObject stockBean, HttpServletRequest request, String answer) {
        this.request = request;
        this.seckillQstBean = seckillQstBean;
        this.stockBean = stockBean;
        this.answer = answer;
    }

    public void addParams(String paramString1, String paramString2) {
        if ((paramString1 != null) && (paramString2 != null))
            this.params.put(paramString1, paramString2);
    }

    public static void main(String[] args) throws Exception {
        SeckillOrderCreator c = new SeckillOrderCreator(new JSONObject(), new JSONObject(), new MockHttpServletRequest(), "AAA");
        System.out.println(c.generalRequestUrl());
    }

    public String generalRequestUrl() throws Exception {
        String baseUrl = "http://api.m.taobao.com/rest/api3.do?";
        DetailSecKillOrderRequest detailSecKillOrderRequest = new DetailSecKillOrderRequest();
        detailSecKillOrderRequest.setQuantity(1);
        detailSecKillOrderRequest.setItemId(request.getParameter("itemId"));
        detailSecKillOrderRequest.setSkuId(request.getParameter("skuId"));
        detailSecKillOrderRequest.setSid(request.getParameter("sid"));   //应该是登录后生成的固定的id
        detailSecKillOrderRequest.setDetailValidKeyName(stockBean.getString("timkn"));
        detailSecKillOrderRequest.setDetailValidKeyValue(stockBean.getString("timk"));
        detailSecKillOrderRequest.setEncryptStr(seckillQstBean.getString("sign")); //问题来的串
        detailSecKillOrderRequest.setAnswer(answer);
        detailSecKillOrderRequest.setSupportAsync(false);

        addParams("data", JSON.toJSONString(detailSecKillOrderRequest, SerializerFeature.WriteMapNullValue));
        addParams("v", detailSecKillOrderRequest.version);
        addParams("api", detailSecKillOrderRequest.API_NAME);
        addParams("ttid", "600000@taobao_android_4.6.0");
        addParams("appKey", "21646297");
        addParams("t", String.valueOf(stockBean.getLongValue("now") / 1000L));
        addParams("imei", "860311021335625");
        addParams("imsi", "460023803112482");
        addParams("deviceId", "Ahlp6SYwRmi0D4_tvCtyzFiYTA65YXKOltP7DW4PyACg");
        String ecodeStr = request.getParameter("ecode");
        String ecode = new String(DESede.decryptMode("460023803112482".getBytes(), Base64.decodeBase64(ecodeStr.getBytes("ISO-8859-1"))), "ISO-8859-1");
        addParams("ecode", ecode);
        String appsecret = getAppsecret();
        String str5 = sign(this.params, appsecret);
        this.params.remove("ecode");
        int i = this.params.size();
        Object[] arrayOfObject1 = this.params.keySet().toArray();
        Object[] arrayOfObject2 = this.params.values().toArray();
        StringBuffer paramBuffer = new StringBuffer();
        paramBuffer.append(baseUrl);
        paramBuffer.append("sign=");
        paramBuffer.append(str5);
        for (int j = 0; j < i; j++) {
            paramBuffer.append("&");
            paramBuffer.append((String) arrayOfObject1[j]);
            paramBuffer.append("=");
            paramBuffer.append(URLEncoder.encode(String.valueOf(arrayOfObject2[j]), "utf-8"));
        }
        return paramBuffer.toString().replace(" ", "%20");
    }

    public static String sign(TreeMap<String, String> paramTreeMap, String appsecret) throws Exception {
        String appKey = (String) paramTreeMap.get("appKey");
        String str3 = appsecret;
        String str4 = (String) paramTreeMap.get("api");
        String str5 = (String) paramTreeMap.get("v");
        String str6 = (String) paramTreeMap.get("imei");
        String str7 = (String) paramTreeMap.get("imsi");
        String str8 = (String) paramTreeMap.get("data");
        String str9 = (String) paramTreeMap.get("t");
        String str10 = (String) paramTreeMap.get("ecode");
        String str11 = mde5ToHex(appKey);
        StringBuffer localStringBuffer = new StringBuffer();
        if ((str10 != null) || ("".equals(str10))) {
            localStringBuffer.append(str10);
            localStringBuffer.append("&");
        }
        localStringBuffer.append(str3);
        localStringBuffer.append("&");
        localStringBuffer.append(str11);
        localStringBuffer.append("&");
        localStringBuffer.append(str4);
        localStringBuffer.append("&");
        localStringBuffer.append(str5);
        localStringBuffer.append("&");
        localStringBuffer.append(str6);
        localStringBuffer.append("&");
        localStringBuffer.append(str7);
        localStringBuffer.append("&");
        localStringBuffer.append(mde5ToHex(str8));
        localStringBuffer.append("&");
        localStringBuffer.append(str9);
        try {
            String str1 = mde5ToHex(localStringBuffer.toString());
            return str1;
        } catch (Exception localException) {
        }
        return "";
    }

    private static String mde5ToHex(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes("UTF-8"));
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        byte[] arrayOfByte = new byte[1024];
        for (int i = in.read(arrayOfByte, 0, 1024); i > -1; i = in.read(arrayOfByte, 0, 1024))
            localMessageDigest.update(arrayOfByte, 0, i);
        String str = bytesToHexString(localMessageDigest.digest());
        return str;
    }

    public static String bytesToHexString(byte[] paramArrayOfByte) {
        StringBuilder stringbuilder = new StringBuilder("");
        String s;
        if (paramArrayOfByte == null || paramArrayOfByte.length <= 0) {
            s = null;
        } else {
            for (int i = 0; i < paramArrayOfByte.length; i++) {
                String s1 = Integer.toHexString(255 & paramArrayOfByte[i]);
                if (s1.length() < 2)
                    stringbuilder.append(0);
                stringbuilder.append(s1);
            }

            s = stringbuilder.toString();
        }
        return s;
    }

    static String appsecret = null;
    static String appsecretSigned = "756h;d8g:429d;57cf<j8g5f:f3:d<d4";

    public static String getAppsecret() {
        if ((appsecret == null) || ("".equals(appsecret))) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < appsecretSigned.length(); i++) {
            char c = (char) (appsecretSigned.charAt(i) - i % 5);
            sb.append(c);
            }
            appsecret = sb.toString();
        }
        return appsecret;
    }
}


